const Router = require('koa-router');
const router = new Router();
const md5 = require('blueimp-md5');
const base64 = require('js-base64')['Base64'];
const uuid = require('node-uuid');

// 请求
const siteService = require('../services/siteService');
const errorService = require('../services/errorService');
// 获取基础信息
const until = require('../middlewares/until')
// 基础配置文件
const config = require('../config/config');


router.use(async(ctx, next) => {
    const token = ctx.cookies.get('author');
    const url = ctx.url;
    // 排除请求接口
    if(url.indexOf('/api/login') < 0){
        if(token){
            const tokenParams = base64.decode(token);
            const date = tokenParams.split(',')[1];
            const currentDate = new Date().getTime();
            if(currentDate < date){
                const params = {
                    token: token
                }
                const res = await siteService.get('validToken',params);
                if(res){
                    return await next();
                }
            }
        }
        return ctx.body = {
            msg: '登录信息失效，请求失败',
            code: 600001,
            success: false,
            status: 401
        }
    }
    
    await next();
});

/**
 * 请求登录页面
*/
router.post('/api/login', async (ctx, next) => {
    const params = ctx.request.body;
    
    if(!params['userName']){
        return  ctx.body = {
            success: false,
            msg: '用户名参数错误',
            code: 600001,
        };
    }
    if(!params['password']){
        return ctx.body = {
            success: false,
            msg: '用户密码参数错误',
            code: 600002

        };
    }
    params['password'] = md5(params['password'], config.PRIVATE_KEY);
    
    const result = await siteService.get('login', params);
    const date = new Date().getTime() + 24*60*60*1000;

    if(result.length){
        const token = base64.encode(`${uuid.v1()},${date}`);
        let userParams = {
            token: token,
            userId: result[0]['user_id']
        };

        // 数据库写入token
        const res =  await siteService.get('updateUser', userParams);

        if(res){
            ctx.cookies.set('author', token);
            return ctx.body = {
                success: true,
                msg: '用户登录成功',
                code: 300000,
                data: result[0]['user_id']
            };
        }
    }

    return ctx.body = {
        success: false,
        msg: '用户名或者密码错误',
        code: 600003,
    };
    
})


/**
 * 提交资料
*/
router.post('/api/uploadError', async (ctx, next) => {
    const params = ctx.request.body;
    // params['browserId'] = until.getBrowser(ctx);
    // params['systemId'] = until.getSystem(ctx);
    errorService.get('uploadError', params);
    ctx.body = {
        msg: '提交成功',
        error: 300000,
        success: true
    }
})

/**
 * 获取错误列表
 */
router.get('/api/getRecordList', async (ctx, next)=> {
    
    let res = {};
    const params = ctx.query;
    res = await errorService.get('getRecord', params);
    ctx.body = {
        data: res,
        success: true,
        code: 300000
    }
})

/**
 * 获取错详情
 */
router.get('/api/getRecordDetail', async (ctx, next)=> {
    
    let res = {};
    const params = ctx.query;
    if(params['errorId']){
        res = await errorService.get('getRecordDetail', params);
        ctx.body = {
            data: res[0],
            success: true,
            code: 300000
        }
    }else{
        ctx.body = {
            msg: '参数错误',
            success: false,
            code: 600000
        }
    }

})
module.exports = router;
